package com.mcxx.modules.base.service.read;

import com.mcxx.common.exception.BizException;
import com.mcxx.easyrule.template.RuleEngineTemplate;
import com.mcxx.modules.miniSalvation.family.service.read.SpecialPeopleReadService;
import com.mcxx.modules.miniSalvation.order.dto.OrderStateVerifyDTO;
import com.mcxx.modules.miniSalvation.order.param.ActivitiParam;
import com.mcxx.modules.miniSalvation.order.param.OrderBizStateParamNew;
import com.mcxx.modules.temporary.order.dto.TmpOrderStateVerifyDTO;
import com.mcxx.util.CommonUtil;
import com.mcxx.util.Constant;
import com.mcxx.util.FailureCode;
import com.yinhai.ta404.core.security.vo.UserAccountVo;
import com.yinhai.ta404.core.service.BaseService;
import com.yinhai.ta404.core.transaction.annotation.TaTransactional;
import org.jeasy.rules.api.Facts;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


@Service
@TaTransactional(readOnly = true)
public class RuleEngineReadService extends BaseService{
    @Autowired
    private RuleEngineTemplate ruleEngineTemplate;
    @Autowired
    private ActivitiReadService activitiReadService;
    @Autowired
    private SpecialPeopleReadService specialPeopleReadService;


    public void getBizStateRuleThrow(String bizStateType, OrderStateVerifyDTO orderStateVerifyDTO, UserAccountVo userAccountVo){

        if(bizStateType.equals(Constant.OrderBizStateType.TOWN_DELETE) && orderStateVerifyDTO.getCheckIngCount() > 0){
            throw new BizException(FailureCode.ERR_20005);
        }


        if(Constant.OrderType.RECHECK.equals(orderStateVerifyDTO.getType())){
            getRecheckBizStateRuleThrow(bizStateType,orderStateVerifyDTO,userAccountVo);
            return;
        }


        if(orderStateVerifyDTO.getReportNum() <= 0 && !bizStateType.equals(Constant.OrderBizStateType.START_TOWN_IN_HOUSE)
                && !bizStateType.equals(Constant.OrderBizStateType.COMPLETE_TOWN_IN_HOUSE)
                && !bizStateType.equals(Constant.OrderBizStateType.ORDER_EDIT)
                && !bizStateType.equals(Constant.OrderBizStateType.TOWN_REVOKE)
                && !bizStateType.equals(Constant.OrderBizStateType.TOWN_DELETE)){
            throw new BizException(FailureCode.ERR_20005);
        }




//        if(bizStateType.equals(Constant.OrderBizStateType.ORDER_EDIT)){
//            orderStateVerifyDTO.setNextState(orderStateVerifyDTO.getState());
//            orderStateVerifyDTO.setNextBizState(orderStateVerifyDTO.getNextBizState());




        if(CommonUtil.invalidArgs(orderStateVerifyDTO.getNextCondition())){
            orderStateVerifyDTO.setNextCondition("1");
        }


        OrderBizStateParamNew orderBizStateParam = this.readRule(orderStateVerifyDTO.getOrderId(), bizStateType);


        this.verifyBizStateThrow(orderStateVerifyDTO, orderBizStateParam);


        if(Constant.OrderBizStateType.ActivitiTypeList.contains(bizStateType)){
            this.readActivitiThrow(orderStateVerifyDTO, userAccountVo, bizStateType);
        }


        if(Constant.OrderBizStateType.TOWN_SUBMIT.equals(bizStateType)){
            int cntNum = specialPeopleReadService.cntFamilySpecialNum(orderStateVerifyDTO.getFamilyId());
            if(cntNum > 0){
                orderStateVerifyDTO.setNextState(Constant.BizStateNew.COUNTY_WAIT_IN_HOUSE);
                orderStateVerifyDTO.setNextBizState(Constant.BizStateNew.COUNTY_WAIT_IN_HOUSE);
            }
        }
    }


    public boolean getBizStateRule(String bizStateType, OrderStateVerifyDTO orderStateVerifyDTO, UserAccountVo userAccountVo){

        if(bizStateType.equals(Constant.OrderBizStateType.TOWN_DELETE) && orderStateVerifyDTO.getCheckIngCount() > 0){
            return false;
        }

        if(Constant.OrderType.RECHECK.equals(orderStateVerifyDTO.getType())){
            return getRecheckBizStateRule(bizStateType,orderStateVerifyDTO,userAccountVo);
        }

        if(orderStateVerifyDTO.getReportNum() <= 0 && !bizStateType.equals(Constant.OrderBizStateType.START_TOWN_IN_HOUSE)
                && !bizStateType.equals(Constant.OrderBizStateType.COMPLETE_TOWN_IN_HOUSE)
                && !bizStateType.equals(Constant.OrderBizStateType.ORDER_EDIT)
                && !bizStateType.equals(Constant.OrderBizStateType.TOWN_DELETE)){
            return false;
        }

        if(bizStateType.equals(Constant.OrderBizStateType.TOWN_DELETE) && orderStateVerifyDTO.getCheckIngCount() > 0){
            return false;
        }

//        if(bizStateType.equals(Constant.OrderBizStateType.ORDER_EDIT)){
//            orderStateVerifyDTO.setNextState(orderStateVerifyDTO.getState());
//            orderStateVerifyDTO.setNextBizState(orderStateVerifyDTO.getNextBizState());




        if(CommonUtil.invalidArgs(orderStateVerifyDTO.getNextCondition())){
            orderStateVerifyDTO.setNextCondition("1");
        }


        OrderBizStateParamNew orderBizStateParam = this.readRule(orderStateVerifyDTO.getOrderId(), bizStateType);


        boolean nextMark = this.verifyBizState(orderStateVerifyDTO, orderBizStateParam);
        if(!nextMark){

            return nextMark;
        }


        if(Constant.OrderBizStateType.ActivitiTypeList.contains(bizStateType)){

            nextMark = this.readActiviti(orderStateVerifyDTO, userAccountVo, bizStateType);
            if(!nextMark){

                return nextMark;
            }
        }


        if(Constant.OrderBizStateType.TOWN_SUBMIT.equals(bizStateType)){
            int cntNum = specialPeopleReadService.cntFamilySpecialNum(orderStateVerifyDTO.getFamilyId());
            if(cntNum > 0){
                orderStateVerifyDTO.setNextState(Constant.BizStateNew.COUNTY_WAIT_IN_HOUSE);
                orderStateVerifyDTO.setNextBizState(Constant.BizStateNew.COUNTY_WAIT_IN_HOUSE);
            }
        }
        return  nextMark;
    }


    private OrderBizStateParamNew readRule(String orderId, String bizStateType){
        OrderBizStateParamNew orderBizStateParam = new OrderBizStateParamNew(orderId, bizStateType);
        Facts facts = new Facts();

        facts.put("orderBizStateParam", orderBizStateParam);

        ruleEngineTemplate.fire("orderBizStateRules", facts);
        return orderBizStateParam;
    }


    private void verifyBizStateThrow(OrderStateVerifyDTO orderStateVerifyDTO, OrderBizStateParamNew orderBizStateParam){

        if(!orderBizStateParam.getCurStep().get("curStateList").contains(orderStateVerifyDTO.getState())
            || !orderBizStateParam.getCurStep().get("curBizStateList").contains(orderStateVerifyDTO.getBizState())){
            throw new BizException("-1", "[" + orderStateVerifyDTO.getIdcard() + "]当前业务的办理状态为【" + Constant.BizStateNew.BizStateChineseNameMap.get(orderStateVerifyDTO.getBizState()) + "】，无法执行当前操作");
        }

        if(!orderBizStateParam.getNextBizState().containsKey(orderStateVerifyDTO.getNextCondition())){
            throw new BizException("-1", "业务办理流程配置错误，请联系管理员");
        }

        orderStateVerifyDTO.setNextBizState(orderBizStateParam.getNextBizState().get(orderStateVerifyDTO.getNextCondition()));
    }


    private boolean verifyBizState(OrderStateVerifyDTO orderStateVerifyDTO, OrderBizStateParamNew orderBizStateParam){

        if(!orderBizStateParam.getCurStep().get("curStateList").contains(orderStateVerifyDTO.getState())
            || !orderBizStateParam.getCurStep().get("curBizStateList").contains(orderStateVerifyDTO.getBizState())){
            return false;
        }

        if(!orderBizStateParam.getNextBizState().containsKey(orderStateVerifyDTO.getNextCondition())){
            return false;
        }

        orderStateVerifyDTO.setNextBizState(orderBizStateParam.getNextBizState().get(orderStateVerifyDTO.getNextCondition()));
        return true;
    }


    private void readActivitiThrow(OrderStateVerifyDTO orderStateVerifyDTO, UserAccountVo userAccountVo, String bizStateType){

        ActivitiParam activitiParam = new ActivitiParam(orderStateVerifyDTO.getState(), orderStateVerifyDTO.getNextCondition(),
                orderStateVerifyDTO.getSalvMoney(), orderStateVerifyDTO.getBusinessType());
        if(Constant.OrderBizStateType.COMPLETE_TOWN_IN_HOUSE.equals(bizStateType)){

            activitiParam.setSalvMoney(null);
        }

        String nextActviti = activitiReadService.getOrderNextActviti(activitiParam, userAccountVo.getRoles());

        if("-1".equals(nextActviti) || CommonUtil.invalidArgs(nextActviti)){
            throw new BizException("-1", "当前账号没有操作权限");
        }

        orderStateVerifyDTO.setNextState(nextActviti);
    }


    private boolean readActiviti(OrderStateVerifyDTO orderStateVerifyDTO, UserAccountVo userAccountVo, String bizStateType){

        ActivitiParam activitiParam = new ActivitiParam(orderStateVerifyDTO.getState(), orderStateVerifyDTO.getNextCondition(),
                orderStateVerifyDTO.getSalvMoney(), orderStateVerifyDTO.getBusinessType());
        if(Constant.OrderBizStateType.COMPLETE_TOWN_IN_HOUSE.equals(bizStateType)){

            activitiParam.setSalvMoney(null);
        }

        String nextActviti = activitiReadService.getOrderNextActviti(activitiParam, userAccountVo.getRoles());

        if("-1".equals(nextActviti) || CommonUtil.invalidArgs(nextActviti)){
            return false;
        }

        orderStateVerifyDTO.setNextState(nextActviti);
        return true;
    }


    public void getTempBizStateRuleThrow(String bizStateType, TmpOrderStateVerifyDTO orderStateVerifyDTO, UserAccountVo userAccountVo) {

        if(bizStateType.equals(Constant.OrderBizStateType.TOWN_DELETE) && orderStateVerifyDTO.getCheckIngCount() > 0){
            throw new BizException(FailureCode.ERR_20005);
        }

        if(orderStateVerifyDTO.getReportNum() < 1
                && orderStateVerifyDTO.getCheckIngCount() > 0
                && (bizStateType.equals(Constant.TmpOrderBizStateType.TOWN_SUBMIT)
                    || bizStateType.equals(Constant.TmpOrderBizStateType.COMPLETE_FIRST_AUDIT)
                    || bizStateType.equals(Constant.TmpOrderBizStateType.COMPLETE_TOWN_AUDIT)
                    || bizStateType.equals(Constant.TmpOrderBizStateType.COMPLETE_COUNTY_APPROVE))){
            throw new BizException(FailureCode.ERR_20005);
        }

//        if(bizStateType.equals(Constant.OrderBizStateType.ORDER_EDIT)){
//            orderStateVerifyDTO.setNextState(orderStateVerifyDTO.getState());
//            orderStateVerifyDTO.setNextBizState(orderStateVerifyDTO.getNextBizState());



        if(CommonUtil.invalidArgs(orderStateVerifyDTO.getNextCondition())){
            orderStateVerifyDTO.setNextCondition("1");
        }

        OrderBizStateParamNew orderBizStateParam = this.readTmpRule(orderStateVerifyDTO.getOrderId(), bizStateType);


        this.verifyTmpBizStateThrow(orderStateVerifyDTO, orderBizStateParam);


        if(Constant.TmpOrderBizStateType.ActivitiTypeList.contains(bizStateType)){
            this.readTmpActivitiThrow(orderStateVerifyDTO, userAccountVo, bizStateType);
        }
    }

    private OrderBizStateParamNew readTmpRule(String orderId, String bizStateType){
        OrderBizStateParamNew orderBizStateParam = new OrderBizStateParamNew(orderId, bizStateType);
        Facts facts = new Facts();

        facts.put("orderBizStateParam", orderBizStateParam);

        ruleEngineTemplate.fire("tmpOrderBizStateRules", facts);
        return orderBizStateParam;
    }

    private void verifyTmpBizStateThrow(TmpOrderStateVerifyDTO orderStateVerifyDTO, OrderBizStateParamNew orderBizStateParam){

        if(!orderBizStateParam.getCurStep().get("curStateList").contains(orderStateVerifyDTO.getState())
                || !orderBizStateParam.getCurStep().get("curBizStateList").contains(orderStateVerifyDTO.getBizState())){
            throw new BizException("-1", "[" + orderStateVerifyDTO.getIdcard() + "]当前业务的办理状态为【" + Constant.BizStateTmpNew.BizStateChineseNameMap.get(orderStateVerifyDTO.getBizState()) + "】，无法执行当前操作");
        }

        if(!orderBizStateParam.getNextBizState().containsKey(orderStateVerifyDTO.getNextCondition())){
            throw new BizException("-1", "业务办理流程配置错误，请联系管理员");
        }

        orderStateVerifyDTO.setNextBizState(orderBizStateParam.getNextBizState().get(orderStateVerifyDTO.getNextCondition()));
    }

    private void readTmpActivitiThrow(TmpOrderStateVerifyDTO orderStateVerifyDTO, UserAccountVo userAccountVo, String bizStateType){

        ActivitiParam activitiParam = new ActivitiParam(orderStateVerifyDTO.getState(), orderStateVerifyDTO.getNextCondition(),
                orderStateVerifyDTO.getSalvMoney(), Constant.BusinessCode.LINSHI);
        if(Constant.TmpOrderBizStateType.COMPLETE_TOWN_IN_HOUSE.equals(bizStateType)){

            activitiParam.setSalvMoney(null);
        }

        if(Constant.TmpOrderBizStateType.COMPLETE_TOWN_AUDIT.equals(bizStateType) && Constant.BizStateTmpNew.APPROVE_REJECT.equals(orderStateVerifyDTO.getState())) {

            activitiParam.setNextCondition("1"+activitiParam.getNextCondition());
        }

        String nextActviti = activitiReadService.getOrderNextActviti(activitiParam, userAccountVo.getRoles());

        if("-1".equals(nextActviti) || CommonUtil.invalidArgs(nextActviti)){
            throw new BizException("-1", "当前账号没有操作权限");
        }

        orderStateVerifyDTO.setNextState(nextActviti);
    }



    public void getRecheckBizStateRuleThrow(String bizStateType, OrderStateVerifyDTO orderStateVerifyDTO, UserAccountVo userAccountVo){

        if(bizStateType.equals(Constant.OrderBizStateType.START_TOWN_AUDIT) && orderStateVerifyDTO.getCheckIngCount() > 0 && orderStateVerifyDTO.getCheckIngUpload() == 0){
            throw new BizException(FailureCode.ERR_20005);
        }

//        if(bizStateType.equals(Constant.OrderBizStateType.ORDER_EDIT)){
//            orderStateVerifyDTO.setNextState(orderStateVerifyDTO.getState());
//            orderStateVerifyDTO.setNextBizState(orderStateVerifyDTO.getNextBizState());



        if(CommonUtil.invalidArgs(orderStateVerifyDTO.getNextCondition())){
            orderStateVerifyDTO.setNextCondition("1");
        }

        OrderBizStateParamNew orderBizStateParam = this.readRecheckRule(orderStateVerifyDTO.getOrderId(), bizStateType);


        this.verifyRecheckBizStateThrow(orderStateVerifyDTO, orderBizStateParam);


        if(Constant.OrderBizStateType.ActivitiTypeList.contains(bizStateType)){

            if(Constant.OrderBizStateType.COMPLETE_NOTICE.equals(bizStateType)){
                orderStateVerifyDTO.setNextCondition("1"+orderStateVerifyDTO.getNextCondition());
            }

            if(Constant.OrderBizStateType.COMPLETE_TOWN_IN_HOUSE.equals(bizStateType)||Constant.OrderBizStateType.COMPLETE_TOWN_IN_HOUSE_AGAIN.equals(bizStateType)){
                orderStateVerifyDTO.setNextCondition("1");
            }
            this.readRecheckActivitiThrow(orderStateVerifyDTO, userAccountVo, bizStateType);
        }

        if(Constant.OrderBizStateType.TOWN_SUBMIT.equals(bizStateType)){
            int cntNum = specialPeopleReadService.cntFamilySpecialNum(orderStateVerifyDTO.getFamilyId());
            if(cntNum > 0){
                orderStateVerifyDTO.setNextState(Constant.BizStateNew.COUNTY_WAIT_IN_HOUSE);
                orderStateVerifyDTO.setNextBizState(Constant.BizStateNew.COUNTY_WAIT_IN_HOUSE);
            }
        }
    }

    public boolean getRecheckBizStateRule(String bizStateType, OrderStateVerifyDTO orderStateVerifyDTO, UserAccountVo userAccountVo){

//        if(bizStateType.equals(Constant.OrderBizStateType.ORDER_EDIT)){
//            orderStateVerifyDTO.setNextState(orderStateVerifyDTO.getState());
//            orderStateVerifyDTO.setNextBizState(orderStateVerifyDTO.getNextBizState());



        if(CommonUtil.invalidArgs(orderStateVerifyDTO.getNextCondition())){
            orderStateVerifyDTO.setNextCondition("1");
        }

        OrderBizStateParamNew orderBizStateParam = this.readRecheckRule(orderStateVerifyDTO.getOrderId(), bizStateType);


        boolean nextMark = this.verifyBizState(orderStateVerifyDTO, orderBizStateParam);
        if(!nextMark){

            return nextMark;
        }


        if(Constant.OrderBizStateType.ActivitiTypeList.contains(bizStateType)){

            if(Constant.OrderBizStateType.COMPLETE_NOTICE.equals(bizStateType)){
                orderStateVerifyDTO.setNextCondition("1"+orderStateVerifyDTO.getNextCondition());
            }

            nextMark = this.readActiviti(orderStateVerifyDTO, userAccountVo, bizStateType);
            if(!nextMark){

                return nextMark;
            }
        }

        if(Constant.OrderBizStateType.TOWN_SUBMIT.equals(bizStateType)){
            int cntNum = specialPeopleReadService.cntFamilySpecialNum(orderStateVerifyDTO.getFamilyId());
            if(cntNum > 0){
                orderStateVerifyDTO.setNextState(Constant.BizStateNew.COUNTY_WAIT_IN_HOUSE);
                orderStateVerifyDTO.setNextBizState(Constant.BizStateNew.COUNTY_WAIT_IN_HOUSE);
            }
        }
        return  nextMark;
    }

    private OrderBizStateParamNew readRecheckRule(String orderId, String bizStateType){
        OrderBizStateParamNew orderBizStateParam = new OrderBizStateParamNew(orderId, bizStateType);
        Facts facts = new Facts();

        facts.put("orderBizStateParam", orderBizStateParam);

        ruleEngineTemplate.fire("recheckOrderBizStateRules", facts);
        return orderBizStateParam;
    }

    private void verifyRecheckBizStateThrow(OrderStateVerifyDTO orderStateVerifyDTO, OrderBizStateParamNew orderBizStateParam){

        if(!orderBizStateParam.getCurStep().get("curStateList").contains(orderStateVerifyDTO.getState())
                || !orderBizStateParam.getCurStep().get("curBizStateList").contains(orderStateVerifyDTO.getBizState())){
            throw new BizException("-1", "[" + orderStateVerifyDTO.getIdcard() + "]当前业务的办理状态为【" + Constant.BizStateNew.BizStateChineseNameMap.get(orderStateVerifyDTO.getBizState()) + "】，无法执行当前操作");
        }

        if(!orderBizStateParam.getNextBizState().containsKey(orderStateVerifyDTO.getNextCondition())){
            throw new BizException("-1", "业务办理流程配置错误，请联系管理员");
        }

        orderStateVerifyDTO.setNextBizState(orderBizStateParam.getNextBizState().get(orderStateVerifyDTO.getNextCondition()));
    }

    private void readRecheckActivitiThrow(OrderStateVerifyDTO orderStateVerifyDTO, UserAccountVo userAccountVo, String bizStateType){

        ActivitiParam activitiParam = new ActivitiParam(orderStateVerifyDTO.getState(), orderStateVerifyDTO.getNextCondition(),
                orderStateVerifyDTO.getSalvMoney(), orderStateVerifyDTO.getBusinessType());
        if(Constant.TmpOrderBizStateType.COMPLETE_TOWN_IN_HOUSE.equals(bizStateType)){

            activitiParam.setSalvMoney(null);
        }

        String nextActviti = activitiReadService.getOrderNextActviti(activitiParam, userAccountVo.getRoles());

        if("-1".equals(nextActviti) || CommonUtil.invalidArgs(nextActviti)){
            throw new BizException("-1", "当前账号没有操作权限");
        }

        orderStateVerifyDTO.setNextState(nextActviti);
    }
}
